package com.ruoyi.quartz.task;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Description:
 * @Author:let_free
 * @Date:2024/11/30/10:45
 **/
@Component
public class CleanTask {
    // 定义多个需要压缩的目录路径
    private static final List<String> DIRECTORIES = Arrays.asList("/path/to/first/directory", "/path/to/second/directory", "/path/to/third/directory");

    // 每天凌晨12点触发定时任务
    @Scheduled(cron = "0 0 0 * * ?")  // 每天0点执行
    public void cleanOldDirectories() throws IOException {
        // 遍历所有需要处理的目录
        for (String directoryPath : DIRECTORIES) {
            File directory = new File(directoryPath);
            if (directory.exists() && directory.isDirectory()) {
                // 获取当前时间并减去24小时（即前一天的时间）
                long currentTime = System.currentTimeMillis();
                long oneDayAgo = currentTime - (24 * 60 * 60 * 1000); // 当前时间减去一天的毫秒数

                // 遍历目录下所有子目录
                File[] subDirs = directory.listFiles(File::isDirectory);
                if (subDirs != null) {
                    for (File subDir : subDirs) {
                        // 获取目录最后修改时间
                        long lastModified = subDir.lastModified();

                        // 如果目录的修改时间在当前时间之前的前一天，进行压缩
                        if (lastModified < oneDayAgo) {
                            compressDirectory(subDir);
                        }
                    }
                }
            }
        }
    }

    /**
     * 压缩目录
     *
     * @param directory 需要压缩的目录
     */
    private void compressDirectory(File directory) throws IOException {
        String zipFileName = directory.getAbsolutePath() + ".zip";  // 压缩后的文件名

        // 创建Zip输出流
        try (ZipOutputStream zipOut = new ZipOutputStream(Files.newOutputStream(Paths.get(zipFileName)))) {
            // 遍历目录中的所有文件
            Files.walk(directory.toPath()).forEach(filePath -> {
                try {
                    // 对于每一个文件，添加到压缩文件中
                    if (Files.isRegularFile(filePath)) {
                        ZipEntry zipEntry = new ZipEntry(directory.toPath().relativize(filePath).toString());
                        zipOut.putNextEntry(zipEntry);
                        Files.copy(filePath, zipOut);
                        zipOut.closeEntry();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }

        // 删除原始目录以释放空间
        deleteDirectory(directory);
    }

    /**
     * 删除目录及其内容
     *
     * @param directory 需要删除的目录
     */
    private void deleteDirectory(File directory) {
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    deleteDirectory(file);
                } else {
                    file.delete();
                }
            }
        }
        directory.delete();  // 删除目录本身
    }
}
